package net.ewon.cape;

import java.io.File;

import net.ewon.config.NaviConfiguration;

import org.apache.catalina.startup.Tomcat;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CapeService {

	private final static Logger logger = Logger.getLogger(CapeService.class);

	private int port;
	private int shutdownPort;
	private String shutdownCommand;
	private String name;

	public static void main(String[] args) throws Exception {

		CapeService capeService = new CapeService();
		capeService.init();
		capeService.start();
	}

	private void init() throws Exception {
		ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:NaviConfig.xml");
//		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
//		ppc.setProperties(naviConfiguration.getProperties());
//		ppc.postProcessBeanFactory(beanFactory);
		
		NaviConfiguration naviConfiguration = (NaviConfiguration) ac.getBean("naviConfiguration");
		
		port = naviConfiguration.getInt("CapeService.port");
		shutdownPort = naviConfiguration.getInt("CapeService.shutdownPort");
		shutdownCommand = naviConfiguration
				.getString("CapeService.shutdownCommand");
		name = naviConfiguration.getString("CapeService.name");
		

	}

	private void start() throws Exception {
		String webappDirLocation = new File("../webapp").getAbsolutePath();

		Tomcat tomcat = new Tomcat();

		tomcat.setPort(port);
		tomcat.getServer().setPort(shutdownPort);
		tomcat.getServer().setShutdown(shutdownCommand);

		String contextPath = "/" + name;
		tomcat.addWebapp(contextPath,
				new File(webappDirLocation).getAbsolutePath());

		logger.info("configuring app with basedir: "
				+ new File("./" + webappDirLocation).getAbsolutePath());

		tomcat.start();
		tomcat.getServer().await();
	}

}
